import message from "@/common/element-plus/message";
/**
 * 表单校验hooks
 * @returns
 */
export const useValidator = () => {
  /**
   * 必填项校验
   * @param {*} message 警告消息
   * @param {*} trigger 触发方式
   * @returns
   */
  const required = (message, trigger = "blur") => {
    return {
      required: true,
      message: message + "不能为空",
      trigger,
    };
  };

  /**
   * 长度校验
   * @param {*} options 
   * @returns 
   */
  const lengthRange = (options) => {
    const { min, max, message } = options;
    return {
      min,
      max,
      message
    };
  };

  const notSpace = (message) => {
    return {
      validator: (_, val, callback) => {
        if (val?.indexOf(" ") !== -1) {
          callback(new Error(message));
        } else {
          callback();
        }
      },
    };
  };

  const notSpecialCharacters = (message) => {
    return {
      validator: (_, val, callback) => {
        if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
          callback(new Error(message));
        } else {
          callback();
        }
      },
    };
  };

  /**
   * 验证表单
   * @param {*} formRef 表单实例
   * @returns
   */
  const validate = async (formRef) => {
    if (!formRef) {
      console.error("form instance is undefined");
      return;
    }
    await formRef.validate((valid, fields) => {
      if (!valid) {
        if (Object.keys(fields).length === 1){
          message.error(fields[Object.keys(fields)[0]][0].message);
        } else {
          message.error("多处有误，请再次填写");
        }
        throw new Error(JSON.stringify(fields));
      }
    });
  };

  /**
   * 重置表单
   * @param {*} formRef 表单实例
   * @returns
   */
  const useResetForm = (formRef) => {
    if (!formRef) {
      console.error("form instance is undefined");
      return;
    }
    formRef.resetFields();
  };

  /**
   * 重置表单验证，保留数据
   * @param {*} formRef 表单实例
   * @returns
   */
  const clearValidate = (formRef) => {
    if (!formRef) {
      console.error("form instance is undefined");
      return;
    }
    formRef.clearValidate();
  };

  return {
    required,
    lengthRange,
    notSpace,
    notSpecialCharacters,
    validate,
    useResetForm,
    clearValidate
  };
};
